/*
* Author: Felix
* Date: 2007/05/10
*
*/
jsx3.require("tibco.admin.enterpriseAssets.EnterpriseAssetsTabInterface");

jsx3.lang.Package.definePackage("tibco.admin.environments.containers", function (machines) {
});

/**
 * Containers
 */
jsx3.lang.Class.defineClass("tibco.admin.environments.containers.Containers",
        jsx3.lang.Object,
        [tibco.admin.environments.EnvironmentsInterface, tibco.admin.plugin.PluginContainerInterface],
        function (plugin) {
            plugin.instance = null
            plugin.prototype.handlers = new Object();

            plugin.prototype.init = function() {
                this.jsxsuper();
                tibco.admin.Main.loadResource("tibco/admin/environments/containers/jss/jss.xml", "tibco.admin", "jss33", "ljss", false);
                tibco.admin.Main.loadResource("tibco/admin/environments/containers/jss/xslt.xml", "tibco.admin", "xslt33", "jss", false);
            }

            plugin.prototype.getNamespace = function() {
                return "tibco.admin";
            }

            plugin.prototype.destroyPlugin = function() {
            }

            plugin.getInstance = function(args) {
                if(!this.instance) {
                    this.instance = new tibco.admin.environments.containers.Containers();
                }
                return this.instance;
            }

            plugin.prototype.setContainerId = function(jsxid) {
                // get row, find containerName, get handler object, call configureContainer with the container id on the handler
                var node = this.matrix.getXML().getRecordNode(jsxid);
                var containerName = node.getAttribute("containerName");
                var handler = this.handlers[containerName];
                var major = node.getAttribute("major");
                var minor = node.getAttribute("minor");
                var maintenance = node.getAttribute("maintenance");
                var fragment = node.getAttribute("fragment");
                if(handler) {
                handler.setContainer(containerName, major, minor, maintenance, fragment);
                if(!this.dialog) {
                    var parent = tibco.admin.Main.getServer().getBodyBlock();
                    this.dialog = tibco.admin.Main.loadUIResource(parent, this.getNamespace(), "tibco/admin/environments/containers/ui/dialog.xml", true);

                }
                else {
                    this.dialog.removeChildren();
                    var pArr = this.dialog.getParent().getDimensions();
                    var dArr = new Object();
                    dArr.L = (pArr.W / 2) - 200;
                    dArr.W = 400;
                    dArr.T = (pArr.H / 2) - 200;
                    dArr.H = 400;
                    this.dialog.setDimensions(dArr);
                    this.resizeDialogIfLarger(this.dialog);
                }
                this.dialog.setModal(jsx3.gui.Dialog.MODAL);
                this.dialog.setVisibility(jsx3.gui.Block.VISIBILITYVISIBLE, true);
                handler.loadComponent(this.dialog.getDescendantOfName("contentBlock"));
                }
            }

            plugin.prototype.resizeDialogIfLarger = function(objJSX) {
                if(objJSX == null) return;
                var parent = objJSX.getParent();
                pArr = parent.getAbsolutePosition(parent.getParent());
                var dOrig = objJSX.getAbsolutePosition(parent);
                var dArr = new Object();
                dArr.L = dOrig.L - pArr.L;
                dArr.T = dOrig.T - pArr.T;
                dArr.W = dOrig.W;
                dArr.H = dOrig.H;
                var changed = false;
                if(dArr.L < 10) {
                    dArr.L = 10;
                    changed = true;
                }
                if(dArr.T < 10) {
                    dArr.T = 10;
                    changed = true;
                }
                if(dArr.W > (pArr.W - 20)) {
                    dArr.L = 10;
                    dArr.W = pArr.W - 20;
                    changed = true;
                }
                if(dArr.H > (pArr.H - 20)) {
                    dArr.T = 10;
                    dArr.H = pArr.H - 20;
                    changed = true;
                }
                if(changed) {
                    objJSX.setDimensions(dArr.L, dArr.T, dArr.W, dArr.H, true);
                }
            };

            plugin.prototype.loadComponent = function(parent) {
                if(!this.loading) {
                    this.loading = true;
                    var me = this;
                    tibco.admin.Main.loadUIResourceAsync(parent, this.getNamespace(), "tibco/admin/environments/containers/ui/containers.xml", me, me.componentLoaded);
                }
            }

            plugin.prototype.onAfterGetPlugins = function() {
                var iter = this.getPluginList().iterator();
                while(iter.hasNext()) {
                    try {
                        var obj = iter.next();
                        try {
                            obj.setEnvId(this.envId);
                            obj.setNodeId(this.nodeId);
                        }
                        catch(ex) {
                            tibco.admin.Main.logException(ex);
                        }
                        this.handlers[obj.getType()] = obj;
                    }
                    catch(ex) {
                        tibco.admin.Main.logException(ex);
                    }
                }

                if(this.nodeId && this.block) {
                    this.callgetAvailableContainersForNode();
                }
            }

            plugin.prototype.setupPlugin = function(plugin) {
                var me = this;
                plugin.callbackTarget = me;
                plugin.beginConfigureCallback = me.beginConfigure;
                plugin.endConfigureCallback = me.endConfigure;
            }

            plugin.prototype.arePluginsInCongigureMode = function() {
                var iter = this.getPluginList().iterator();
                while(iter.hasNext()) {
                    var obj = iter.next();
                    if(obj.isInConfigureMode()) {
                        return true;
                    }
                }
                return false;
            }

            plugin.prototype.beginConfigure = function(objPlugin) {
                this.updateButtons();
            }

            plugin.prototype.endConfigure = function(objPlugin) {
                if(this.dialog) {
                    if(this.dialog.getParent()) {
                    }
                    else {
                        delete this.dialog;
                    }
                }
                else {
                }
                this.updateButtons();
            }

            plugin.prototype.updateButtons = function() {
            }

            plugin.prototype.onAfterComponentUnloaded = function() {
                this.resetComponent();
            }

            plugin.prototype.resetComponent = function() {
                this.nodeId = null;
                this.envId = null;
                this.block = null;
                if(this.isInEditMode()) {
                    this.endEditMode();
                }
                if(this.loading) {
                    delete this.loading;
                }
            }

            plugin.prototype.componentLoaded = function(objEvent) {
                delete this.loading;
                if(objEvent.status == "SUCCESS") {
                    this.block = objEvent.obj;
                    this.block.getDescendantOfName("btnEdit_33").setEnabled((this.nodeState == "Starting") ? jsx3.gui.Form.STATEDISABLED : jsx3.gui.Form.STATEENABLED, true);
                    this.matrix = this.block.getDescendantOfName("mtxContainers_33");
                    var me = this;
                    this.block.handler = me;
                    if(this.getPluginList().size() == 0) {
                        var preLoad = new jsx3.util.List(0);

                        if(!tibco.admin.environments.containers.java || !tibco.admin.environments.containers.java.JavaContainer) {
                            try {
                                tibco.admin.Main.loadClass("tibco/admin/environments/containers/java/JavaContainer.js", "tibco.admin");
                                preLoad.add(tibco.admin.environments.containers.java.JavaContainer, preLoad.size());
                            }
                            catch(ex) {
                                tibco.admin.Main.logException(ex);
                            }
                        }
                        else {
                            preLoad.add(tibco.admin.environments.containers.java.JavaContainer, preLoad.size());
                        }
                        if(!tibco.admin.environments.containers.net || !tibco.admin.environments.containers.net.MSDotNetContainer) {
                            try {
                                tibco.admin.Main.loadClass("tibco/admin/environments/containers/net/MSDotNetContainer.js", "tibco.admin");
                                preLoad.add(tibco.admin.environments.containers.net.MSDotNetContainer, preLoad.size());
                            }
                            catch(ex) {
                                tibco.admin.Main.logException(ex);
                            }
                        }
                        else {
                            preLoad.add(tibco.admin.environments.containers.net.MSDotNetContainer, preLoad.size());
                        }
                        if(!tibco.admin.environments.containers.soap || !tibco.admin.environments.containers.soap.SoapContainer) {
                            try {
                                tibco.admin.Main.loadClass("tibco/admin/environments/containers/soap/SoapContainer.js", "tibco.admin");
                                preLoad.add(tibco.admin.environments.containers.soap.SoapContainer, preLoad.size());
                            }
                            catch(ex) {
                                tibco.admin.Main.logException(ex);
                            }
                        }
                        else {
                            preLoad.add(tibco.admin.environments.containers.soap.SoapContainer, preLoad.size());
                        }

                        this.loadPlugins("tibco.admin.environments.containers.ContainersInterface", preLoad);
                    }
                    else {
                        this.onAfterGetPlugins();
                    }
                    tibco.admin.Main.getServer().getJSXByName("mcUse_33").setValueTemplate(tibco.admin.Main.getServer().getDynamicProperty("@@Containers Enabled View Mode Value Template"));
                    this.block.getDescendantOfName("mtxContainers_33").repaintData();
                }
                else {
                    if(objEvent.exception)
                    {
                        tibco.admin.Main.logException(objEvent.exception, objEvent.message);
                    }
                    else {
                        jsx3.log(objEvent.message);
                    }
                }
            }

            plugin.prototype.getButtonText = function(parent) {
                return tibco.admin.Main.getServer().getDynamicProperty("@@lblSectionTitle_33");
            }

            plugin.prototype.setEnvId = function(id) {
                this.envId = id;
                var iter = this.getPluginList().iterator();
                while(iter.hasNext()) {
                    try {
                        var obj = iter.next();
                        obj.setEnvId(this.envId);
                    }
                    catch(ex) {
                        tibco.admin.Main.logException(ex);
                    }
                }
            }

            plugin.prototype.setNodeState = function(state) {
                this.nodeState = state;
                if(this.block) {
                    this.block.getDescendantOfName("btnEdit_33").setEnabled((state == "Starting") ? jsx3.gui.Form.STATEDISABLED : jsx3.gui.Form.STATEENABLED, true);
                }
            }

            plugin.prototype.setNodeIds = function(arrIds) {
                if(this.isInEditMode()) {
                    if((arrIds && (arrIds.length == 1) && (arrIds[0] != this.nodeId)) || (this.nodeId && (!arrIds || (arrIds.length != 1)))) {
                        tibco.admin.Main.alert(tibco.admin.Main.getServer().getDynamicProperty("@@msgCannotUpdateNodeIdTitle_33"), tibco.admin.Main.getServer().getDynamicProperty("@@msgCannotUpdateNodeIdMessage_33"));
                    }
                    return;
                }
                if(arrIds && (arrIds.length == 1)) {
                    this.nodeId = arrIds[0];
                }
                else {
                    this.nodeId = null;
                }
                var iter = this.getPluginList().iterator();
                while(iter.hasNext()) {
                    try {
                        var obj = iter.next();
                        obj.setEnvId(this.nodeId);
                    }
                    catch(ex) {
                        tibco.admin.Main.logException(ex);
                    }
                }
                if(this.nodeId && this.block) {
                    this.callgetAvailableContainersForNode();
                }
            }

            /*
            * Event handler for edit button
            */
            plugin.btnEdit_onclick = function() {
                plugin.getInstance().callgetAvailableContainersForNode();
                plugin.getInstance().beginEditMode();
                plugin.toggleMode();
            }

            /*
            * Event handler for save button
            */
            plugin.btnSave_onclick = function() {
                //TODO: plugin.do edit now!!!! then call the following on success();
                plugin.getInstance().calladdContainers();

            }

            plugin.prototype.calladdContainers = function() {
                var objService = tibco.admin.Main.loadService(this.getNamespace(), "tibco/admin/environments/containers/rules/addContainers.xml", "addContainers", "addContainers");

                if(tibco.admin.Main.getServer().getEnv("MODE")) {
                    objService.setEndpointURL(tibco.admin.util.ServiceHelper.getContainersEndpointURL());
                }

                //subscribe and call
                objService.nodeId = this.nodeId;
                objService.containers = this.getUsedContainers();
                objService.subscribe(jsx3.net.Service.ON_SUCCESS, plugin.onaddContainersSuccess);
                objService.subscribe(jsx3.net.Service.ON_ERROR, plugin.onaddContainersError);
                objService.subscribe(jsx3.net.Service.ON_INVALID, plugin.onaddContainersInvalid);
                objService.setInboundURL("tibco/admin/environments/containers/xml/addContainers.xml");
                objService.doCall();
            };

            plugin.onaddContainersSuccess = function(objEvent) {
                plugin.getInstance().endEditMode();
                plugin.toggleMode();
            };

            plugin.onaddContainersError = function(objEvent) {
            };

            plugin.onaddContainersInvalid = function(objEvent) {
            };

            /*
            * Event handler for cancel button
            */
            plugin.btnCancel_onclick = function() {
                plugin.getInstance().doCancelEdits();
            }

            plugin.prototype.doCancelEdits = function() {
                this.endEditMode();
                plugin.toggleMode();
            }

            plugin.prototype.getConfirmText = function() {
                return tibco.admin.Main.getServer().getDynamicProperty("@@Confirm Discard Text_33");
            }

            /**
             * Event handler for radio button
             */
            plugin.radBtn_onclick = function(id, value) {

                var server = tibco.admin.Main.getServer();
                var objCDFDocument = server.getCache().getDocument(server.getJSXByName("mtxContainers_33").getXMLId());
                var objRec = objCDFDocument.selectSingleNode("//record[@jsxid='" + id + "']");
                if(objRec) {
                    if(objRec.getAttribute("isAssociatedToNode") != value) {
                        objRec.setAttribute("isAssociatedToNode", value);
                        objRec.setAttribute("isModified", "true");
                    }
                }
            }

            plugin.btnDeactivate_onlick = function() {
                plugin.getInstance().calldeactivateContainers();
            }

            plugin.btnActivate_onlick = function() {
                plugin.getInstance().callactivateContainers();
            }

            plugin.toggleMode = function() {
                var server = tibco.admin.Main.getServer();
                var savecancel = plugin.getInstance().isInEditMode()?jsx3.gui.Block.DISPLAYBLOCK:jsx3.gui.Block.DISPLAYNONE;
                var edit = plugin.getInstance().isInEditMode()?jsx3.gui.Block.DISPLAYNONE:jsx3.gui.Block.DISPLAYBLOCK;
                if(plugin.getInstance().isInEditMode()) {
                    server.getJSXByName("mcUse_33").setValueTemplate(server.getDynamicProperty("@@Containers Enabled Edit Mode Value Template"));
                }
                else {
                    server.getJSXByName("mcUse_33").setValueTemplate(server.getDynamicProperty("@@Containers Enabled View Mode Value Template"));
                }
                server.getJSXByName("btnSave_33").setDisplay(savecancel, true);
                server.getJSXByName("btnCancel_33").setDisplay(savecancel, true);
                server.getJSXByName("btnEdit_33").setDisplay(edit, true);
                plugin.getInstance().callgetAvailableContainersForNode();
            }

            /**
             * WSDL Operations: Get Containers
             */
            plugin.prototype.callgetAvailableContainersForNode = function() {
                var objService = tibco.admin.Main.loadService(this.getNamespace(), "tibco/admin/environments/containers/rules/getAvailableContainersForNode.xml", "getAvailableContainersForNode", "getAvailableContainersForNode");

                if(tibco.admin.Main.getServer().getEnv("MODE")) {
                    objService.setEndpointURL(tibco.admin.util.ServiceHelper.getContainersEndpointURL());
                }

                //subscribe and call
                objService.envId = this.envId;
                objService.nodeId = this.nodeId;
                objService.subscribe(jsx3.net.Service.ON_SUCCESS, plugin.ongetAvailableContainersForNodeSuccess);
                objService.subscribe(jsx3.net.Service.ON_ERROR, plugin.ongetAvailableContainersForNodeError);
                objService.subscribe(jsx3.net.Service.ON_INVALID, plugin.ongetAvailableContainersForNodeInvalid);
                objService.setInboundURL("tibco/admin/environments/containers/xml/getAvailableContainersForNode.xml");
                objService.doCall();
            };

            plugin.prototype.refresh = function() {
                if(!this.isInEditMode()) {
                    this.callgetAvailableContainersForNode();
                }

            }
            plugin.ongetAvailableContainersForNodeSuccess = function(objEvent) {
                //TODO: var now = (transform "mtxContainers_33" into "mtxContainers_edited_33"
                plugin.getInstance().block.getDescendantOfName("selFilterEnable").setValue(tibco.admin.Main.getServer().getDynamicProperty("@@Filter Option All"));
                var doc = objEvent.target.getServer().getCache().getDocument("cacheContainers_33");
                if(doc) {
                    var iter = doc.getChildNodes();
                    while(iter.hasNext()) {
                        var rec = iter.next();
                        var val = rec.getAttribute("major") + "." + rec.getAttribute("minor") + "." + rec.getAttribute("maintenance");
                        var fragment = rec.getAttribute("fragment");
                        if(fragment) {
                            val += " " + fragment;
                        }
                        rec.setAttribute("containerVersion", val);
                        var configure = false;
                        //TODO: change this!!!!
                        var handler = plugin.getInstance().handlers[rec.getAttribute("containerName")];
                        if(rec.getAttribute("isAssociatedToNode") && handler) {
                            configure = handler.hasExtendedConfiguration();
                        }
                        rec.setAttribute("configureText", configure ? tibco.admin.Main.getServer().getDynamicProperty("@@CfgContainer_33") : "");
                    }
                    tibco.admin.environments.containers.Containers.getInstance().tempCacheDoc = doc.cloneDocument();
                }
                plugin.updateButtonStates();
                objEvent.target.getServer().getJSXByName("mtxContainers_33").repaint();
            };

            plugin.ongetAvailableContainersForNodeError = function(objEvent) {
            };

            plugin.ongetAvailableContainersForNodeInvalid = function(objEvent) {
            };

            plugin.prototype.rowSelected = function() {
                plugin.updateButtonStates();
            }

            plugin.updateButtonStates = function() {
                var list = tibco.admin.Main.getServer().getJSXByName("mtxContainers_33").getSelectedNodes();
                var count = list.size();
                var active = 0
                var notActive = 0
                var error = 0
                var markedForActivation = 0
                var markedForDeactivation = 0
                var unknown = 0;
                var nodeRunning = (!plugin.getInstance().nodeState || (plugin.getInstance().nodeState == "Stop Failed") || (plugin.getInstance().nodeState == "Running"));
                var iter = list.iterator();
                while(iter.hasNext()) {
                    var node = iter.next();
                    var state = node.getAttribute("containerState");
                    switch(state) {
                        case "Active":
                            active++;
                            break;
                        case "Not Active":
                            notActive++;
                            break;
                        case "Error":
                            error++;
                            break;
                        case "Marked for Activation":
                            markedForActivation++;
                            break;
                        case "Marked for Deactivation":
                            markedForDeactivation++;
                            break;
                        case "Unknown":
                            unknown++;
                            break;
                        default:
                            unknown++;
                            break;
                    }
                }
                tibco.admin.Main.getServer().getJSXByName("btnActivate_33").setEnabled(nodeRunning && (count > 0) && ((active + markedForDeactivation) == 0) && !plugin.getInstance().isInEditMode(), true);
                tibco.admin.Main.getServer().getJSXByName("btnDeactivate_33").setEnabled(nodeRunning && (count > 0) && ((notActive + markedForActivation) == 0) && !plugin.getInstance().isInEditMode(), true);
            }

            plugin.prototype.getUsedContainers = function() {
                return this.matrix.getXML().selectNodes("//record[@isAssociatedToNode='true']").iterator();
            }

            plugin.prototype.getSelectedContainers = function() {
                return this.matrix.getSelectedNodes().iterator();
            }

            //call this method to begin the service call (eg.service.calldeactivateContainers();)
            plugin.prototype.calldeactivateContainers = function() {
                var objService = tibco.admin.Main.loadService(this.getNamespace(), "tibco/admin/environments/containers/rules/deactivateContainers.xml", "deactivateContainers", "deactivateContainers");
                if(tibco.admin.Main.getServer().getEnv("MODE")) {
                    objService.setEndpointURL(tibco.admin.util.ServiceHelper.getContainersEndpointURL());
                }

                //subscribe and call
                objService.containers = this.getSelectedContainers();
                objService.nodeId = this.nodeId;
                objService.subscribe(jsx3.net.Service.ON_SUCCESS, plugin.ondeactivateContainersSuccess);
                objService.subscribe(jsx3.net.Service.ON_ERROR, plugin.ondeactivateContainersError);
                objService.subscribe(jsx3.net.Service.ON_INVALID, plugin.ondeactivateContainersInvalid);
                objService.setInboundURL("tibco/admin/environments/containers/xml/deactivateContainers.xml");
                objService.doCall();
            };

            plugin.ondeactivateContainersSuccess = function(objEvent) {
                //Refresh data from server to make sure the data is latest and updated.
                plugin.getInstance().callgetAvailableContainersForNode();
            };

            plugin.ondeactivateContainersError = function(objEvent) {
            };

            plugin.ondeactivateContainersInvalid = function(objEvent) {
            };

            //call this method to begin the service call (eg.service.callactivateContainers();)
            plugin.prototype.callactivateContainers = function() {
                var objService = tibco.admin.Main.loadService(this.getNamespace(), "tibco/admin/environments/containers/rules/activateContainers.xml", "activateContainers", "activateContainers");

                if(tibco.admin.Main.getServer().getEnv("MODE")) {
                    objService.setEndpointURL(tibco.admin.util.ServiceHelper.getContainersEndpointURL());
                }

                //subscribe and call
                objService.containers = this.getSelectedContainers();
                objService.nodeId = this.nodeId;
                objService.subscribe(jsx3.net.Service.ON_SUCCESS, plugin.onactivateContainersSuccess);
                objService.subscribe(jsx3.net.Service.ON_ERROR, plugin.onactivateContainersError);
                objService.subscribe(jsx3.net.Service.ON_INVALID, plugin.onactivateContainersInvalid);
                objService.setInboundURL("tibco/admin/environments/containers/xml/activateContainers.xml");
                objService.doCall();
            };

            plugin.onactivateContainersSuccess = function(objEvent) {
                //Refresh data from server to make sure the data is latest and updated.
                plugin.getInstance().callgetAvailableContainersForNode();
            };

            plugin.onactivateContainersError = function(objEvent) {
            };

            plugin.onactivateContainersInvalid = function(objEvent) {
            };

            plugin.prototype.filterResults = function() {
                if(this.tempCacheDoc) {
                    var tempCacheDoc = this.tempCacheDoc;
                    var filterEnable = this.block.getDescendantOfName("selFilterEnable").getText();

                    if(filterEnable == tibco.admin.Main.getServer().getDynamicProperty("@@Filter Option All")) {
                        filterEnable = "All";
                    }
                    if(filterEnable == tibco.admin.Main.getServer().getDynamicProperty("@@Filter Option All Enabled")) {
                        filterEnable = "true";
                    }
                    if(filterEnable == tibco.admin.Main.getServer().getDynamicProperty("@@Filter Option All Not Enabled")) {
                        filterEnable = "false";
                    }

                    this.matrix.setXMLTransformers(tibco.admin.Main.resolveURI("tibco.admin", "tibco/admin/environments/containers/xsl/transform.xsl"));
                    this.matrix.setXSLParam("enable", filterEnable);
                    this.matrix.setSourceXML(tempCacheDoc);
                    this.matrix.repaintData();
                }
            }

            plugin.prototype.getComponentPath = function() {
                return "tibco/admin/environments/containers/component.xml"
            }

            plugin.prototype.buttonSelected = function() {
                if(!this.isInEditMode()) {
                    this.callgetAvailableContainersForNode();
                }
            }
        });